package com.daJiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daJiao.domain.PageParam;
import com.daJiao.domain.SecurityUser;
import com.daJiao.domain.SecurityUserDetails;
import com.daJiao.domain.UserBindRole;
import com.daJiao.entity.SysUser;
import com.daJiao.entity.SysUserRole;
import com.daJiao.enums.DeleteFlagEnums;
import com.daJiao.exception.BusinessException;
import com.daJiao.mapper.SysUserMapper;
import com.daJiao.service.SysRoleService;
import com.daJiao.service.SysUserRoleService;
import com.daJiao.service.SysUserService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>Title:	  UserDetailsServiceImpl <br/> </p>
 * <p>Description 用户service <br/> </p>
 * <p>Company:    医百科技有限公司  <br/> </p>
 *
 * @Author <a href="yangwensheng@100doc.com.cn"/>杨文生</a>  <br/>
 * @Date 2021/12/07 17:45
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysRoleService sysRoleService;

    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public SecurityUser getCurrentUser(SecurityUserDetails securityUserDetails) {
//        SecurityUser securityUser = new SecurityUser();
//        securityUser.setUserId(securityUserDetails.getUserId());
//        securityUser.setUsername(securityUserDetails.getUsername());
//        securityUser.setRealName(securityUserDetails.getRealName());
//        securityUser.setEmail(securityUserDetails.getEmail());
//        securityUser.setPhone(securityUserDetails.getPhone());
//        // 菜单和按钮权限信息
//        securityUser.setAuthorityList(securityUserDetails.getAuthorityList());
//        // 角色信息
//        List<SysUserRole> sysUserRoles = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, securityUserDetails.getUserId()));
//        if(CollectionUtils.isNotEmpty(sysUserRoles)){
//            List<SysRole> roleList = sysRoleService.listByIds(sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
//            securityUser.setAuthRoles(roleList.stream().map(SysRole::getRoleName).collect(Collectors.toList()));
//        }
//        return securityUser;
        return null;
    }

    @Override
    public int saveUser(SysUser user, SecurityUserDetails securityUser) {
        SysUser sysUser = sysUserMapper.loadUserByUsername(user.getUserName());
        if(Objects.nonNull(sysUser)){
            throw new BusinessException("用户信息已经存在，不能重复新增");
        }
        String hash = encoder.encode(user.getPassword());
        user.setPassword(hash);
        return sysUserMapper.insert(user);
    }

    @Override
    public int delete(String id, SecurityUserDetails securityUser) {
        SysUser sysUser = sysUserMapper.selectById(id);
        if(Objects.isNull(sysUser)){
            throw new BusinessException("不合法的id");
        }
        sysUser.setDelFlag(DeleteFlagEnums.DELETE.getStatus());
        sysUser.setUpdateBy(securityUser.getUserId());
        sysUser.setUpdater(securityUser.getRealName());
        sysUser.setUpdateTime(LocalDateTime.now());
        return sysUserMapper.updateById(sysUser);
    }

    @Override
    public Page<SysUser> listPage(PageParam<SysUser> param) {
        return sysUserMapper.listPage(new Page(param.getPageNum(), param.getPageSize()),param.getParam());
    }

    @Override
    public SysUser loadUserByUsername(String userName) {
        return sysUserMapper.loadUserByUsername(userName);
    }

    @Override
    public int updateUserInfo(SysUser user) {
        SysUser sysUser = sysUserMapper.selectById(user.getId());
        if(Objects.isNull(sysUser)){
            throw new BusinessException("不合法的id");
        }
        if(StringUtils.isNotEmpty(user.getPassword())){
            String hash = encoder.encode(user.getPassword());
            user.setPassword(hash);
        }
        user.setUpdateTime(LocalDateTime.now());
        return sysUserMapper.updateById(user);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void userBindRole(UserBindRole userBindRole, SecurityUserDetails securityUser) {
        SysUser sysUser = sysUserMapper.selectById(userBindRole.getUserId());
        if(Objects.isNull(sysUser)){
            throw new BusinessException("不合法的userId");
        }

        // 删除原来的角色用户关系
        sysUserRoleService.batchDeleteByUserId(userBindRole.getUserId());

        // 报错新的用户角色关系
        if(CollectionUtils.isNotEmpty(userBindRole.getRoleIds())){
            List<SysUserRole> userRoles = Lists.newArrayList();
            for (String roleId : userBindRole.getRoleIds()) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userBindRole.getUserId());
                userRoles.add(userRole);
            }
            sysUserRoleService.saveBatch(userRoles);
        }
    }

    @Override
    public List<String> getBindRoleByUserId(String userId) {
        List<SysUserRole> sysUserRoles = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userId));
        return sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
    }
}
